var express = require('express');
var router = express.Router();
var config = require('../config.json');
var http = require('client-http');

/* GET home page. */
router.get('/', function (req, res, next) {
    var user_id = req.query.user_id;
    var user_name = req.query.user_name;
    var avatar_src = req.query.avatar_src;
    var user_email = req.query.user_email;
    var nick_name = req.query.nick_name;
    var mobileno = req.query.mobileno;
    var qqno = req.query.qqno;
    var position = req.query.position;
    var signature = req.query.signature;
    res.render('index', {
        title: 'Express',
        user_id: user_id,
        user_name: user_name,
        avatar_src: avatar_src,
        user_email: user_email,
        nick_name:nick_name,
        mobileno:mobileno,
        qqno:qqno,
        position : position,
        signature:signature,
        host:config.usercenter.host
    });
});

router.get('/oauth/code', function (req, res, next) {
    var code = req.query.code;
    http.request(config.usercenter.token_path, function (data) {
        var dataJson = JSON.parse(data);
        var access_token = dataJson.access_token;
        http.get(config.usercenter.user_path + '?access_token=' + access_token, function (user_data) {
            var userJson = JSON.parse(user_data);
            var user = userJson.user;
            res.render('index', {
                title: 'Express',
                user_id: user._id,
                user_name: user.loginname,
                avatar_src: user.avatar_src,
                user_email: user.email,
                nick_name:user.nick_name,
                mobileno:user.mobileno,
                qqno:user.qqno,
                position : user.position,
                signature:user.signature,
                host:config.usercenter.host
            });
        });
    }, "grant_type=authorization_code&client_id=" + config.usercenter.client_id + "&client_secret=" + config.usercenter.client_secret + "&code=" + code, {"Content-Type": "application/x-www-form-urlencoded"});
});

module.exports = router;
